<template>
  <div>
    <el-row :gutter="20" style="margin-top: 10px">
      <!-- 左侧，信息展示 -->
      <el-col :span="8">
        <div class="grid-content bg-purple">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span style="font-size: 20px">个人信息</span>
            </div>
            <div style="text-align: center;">
              <img :src="personalInfo.avatar" style="
                  width: 200px;
                  height: 200px;
                  border-radius: 50%;
                  margin-bottom: 10px;
                " />
            </div>
            <el-divider></el-divider>
            <div class="personal-relation">
              <div class="relation-item">
                <i class="el-icon-user-solid"></i> 用户名称:
                <div style="float: right; padding-right: 20px">
                  {{ personalInfo.userCode }}
                </div>
              </div>
            </div>
            <el-divider></el-divider>
            <div class="personal-relation">
              <div class="relation-item">
                <i class="el-icon-mobile-phone"></i> 手机号码:
                <div style="float: right; padding-right: 20px">
                  {{ personalInfo.mobile }}
                </div>
              </div>
            </div>
            <el-divider></el-divider>
            <div class="personal-relation">
              <div class="relation-item">
                <i class="el-icon-message"></i> 用户邮箱:
                <div style="float: right; padding-right: 20px">
                  {{ personalInfo.email }}
                </div>
              </div>
            </div>
            <el-divider></el-divider>
            <div class="personal-relation">
              <div class="relation-item">
                <i class="el-icon-s-custom"></i> 用户昵称:
                <div style="float: right; padding-right: 20px">
                  {{ personalInfo.userName }}
                </div>
              </div>
            </div>
            <el-divider></el-divider>
            <div class="personal-relation">
              <div class="relation-item">
                <i class="el-icon-date"></i> 创建日期:
                <div style="float: right; padding-right: 20px">
                  {{ personalInfo.createTime }}
                </div>
              </div>
            </div>
            <el-divider></el-divider>
          </el-card>
        </div>
      </el-col>
      <!-- 右侧，信息修改 -->
      <el-col :span="16">
        <div class="grid-content bg-purple">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span style="font-size: 20px">基本资料</span>
            </div>
            <el-tabs v-model="activeName">
              <!-- 基本资料 -->
              <el-tab-pane label="基本资料" name="basic">
                <div>
                  <el-form label-width="80px" :model="personalUpdForm" size="big" label-position="right"
                    style="margin-top: 20px;" :rules="personalUpdRules" ref="personalUpdRef">
                    <el-form-item prop="image" label="更换头像" v-model="personalUpdForm.image">
                      <el-upload :action="'/api/user/modifyAvatar/' + personalUpdForm.id" :headers="uploadHeaders"
                        accept=".jpg, .png, .gif" list-type="picture-card" :on-exceed="limitError"
                        :on-success="imgSuccess" :on-error="imgError" :show-file-list="false">
                        <i class="el-icon-plus"></i>
                      </el-upload>
                    </el-form-item>
                    <el-form-item label="用户名" prop="userCode">
                      <el-input v-model="personalUpdForm.userCode" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="mobile">
                      <el-input v-model="personalUpdForm.mobile" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="电子邮箱" prop="email">
                      <el-input v-model="personalUpdForm.email" clearable></el-input>
                    </el-form-item>
                  </el-form>
                  <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="updUser">保存</el-button>
                    <el-button type="danger" @click="$router.push('/home')">关闭</el-button>
                  </div>
                </div>
              </el-tab-pane>
              <!-- 修改密码 -->
              <el-tab-pane label="修改密码" name="pass">
                <div>
                  <el-form label-width="80px" :model="passwordUpdForm" size="big" label-position="right"
                    style="margin-top: 20px;" :rules="passwordUpdRules" ref="passwordUpdRef">
                    <el-form-item label="原密码" prop="oldPassword">
                      <el-input v-model="passwordUpdForm.oldPassword" show-password clearable
                        placeholder="请输入原密码"></el-input>
                    </el-form-item>
                    <el-form-item label="新密码" prop="password">
                      <el-input v-model="passwordUpdForm.password" show-password clearable
                        placeholder="请输入新密码"></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="repeatPassword">
                      <el-input v-model="passwordUpdForm.repeatPassword" show-password clearable
                        placeholder="请确认新密码"></el-input>
                    </el-form-item>
                  </el-form>
                  <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="updPassword">提交</el-button>
                    <el-button type="danger" @click="$router.push('/home')">关闭</el-button>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router'
import { get, put, post, del, tip, export2excel, getLocalToken } from "@/common";
import { Search, Edit, Check, Message, Star, Delete } from '@element-plus/icons-vue'

const router = useRouter(); // 获取路由器

const tipsExist = ref(false)
let userInfo = reactive({})

const personalUpdForm = reactive({
  id: '',
  userCode: '',
  mobile: '',
  email: '',
  image: ''
})
const passwordUpdForm = reactive({
  id: '',
  oldPassword: '',
  password: '',
  repeatPassword: ''
})

// 图片上传时的请求头
const uploadHeaders = reactive({
  Authorization: getLocalToken(),
})

const activeName = ref("basic")

const personalUpdRules = reactive({
  userCode: [
    { required: true, message: '请输入新用户名', trigger: 'blur' },
    {
      min: 3,
      max: 10,
      message: '长度在 3 到 10 个字符',
      trigger: 'blur',
    },
  ],
  mobile: [
    { required: true, message: '请输入手机', trigger: 'blur' },
    { pattern: /^1\d{10}$/, message: '手机号格式不正确', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { pattern: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/, message: '邮箱格式不正确', trigger: 'blur' },
  ]
})

const validatorPassword = function(rule, value, callback) {
  if (passwordUpdForm.password !== passwordUpdForm.repeatPassword) {
    callback(new Error('两次输入的密码不一致'))
  }
  callback();
}

const passwordUpdRules = reactive({
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 3, max: 15,message: '长度在 3 到 15 个字符',trigger: 'blur'},
  ],
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' },
  ],
  repeatPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validatorPassword, trigger: 'blur' }
  ]
})

const personalInfo = ref({
  userId: null,
  userCode: "",
  userName: "",
  userPwd: "",
  userType: null,
  createTime: "",
  getCode: null,
  mobile: "",
  email: "",
  avatar: ""
})
// 获取用户信息
const loadUserInfo = () => {
  userInfo = JSON.parse(localStorage.getItem('currUser'))

  personalUpdForm.id = userInfo.userId;
  passwordUpdForm.id = userInfo.userId;

  get("/user/" + userInfo.userId).then(res => {
    personalInfo.value = res.data;

    // 如果没有头像，则显示默认头像
    if(!personalInfo.value.avatar){
      personalInfo.value.avatar = './imgs/avatar.jpg'
    }
  
    personalUpdForm.userCode = res.data.userCode;
    personalUpdForm.mobile = res.data.mobile;
    personalUpdForm.email = res.data.email;
  })
}
loadUserInfo()


// 修改个人信息
const personalUpdRef = ref()
const updUser = async () =>  {
  await personalUpdRef.value.validate()
  const { data: res } = await put('/user/modifySelf', personalUpdForm)
  if (res.status != 200) {
    return tip.error(res.msg)
  }

  tip.success('修改个人资料成功')
  loadUserInfo()
}

// 修改密码
const passwordUpdRef = ref()
const updPassword = async () =>  {
  await passwordUpdRef.value.validate()
  const res = await put('/user/modifyPwd', passwordUpdForm)
  console.log(res)
  if (!res.success) {
    return tip.error(res.msg)
  }

  tip.success('修改密码成功')

  passwordUpdRef.value.resetFields()

  loadUserInfo();
}

const emits = defineEmits(['update-user-info']) // 自定义事件
// 头像上传成功的回调
const imgSuccess = (res, file) => {
  if (! res.success) {
    tip.error(res.msg)
    return;
  }
  personalInfo.value.avatar = res.data

  // 触发自定义事件，更新父组件的头像
  emits('update-user-info')
}

const imgError = res => {
  tip.error("上传失败");
}
const limitError = () => {
  tip.error("上传受限");
}
</script>

<style lang="less" scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
}

//文本样式区
.name-role {
  font-size: 16px;
  padding: 5px;
  text-align: center;
}

.sender {
  text-align: center;
}

.personal-relation {
  font-size: 16px;
  padding: 0px 5px 15px;
  margin-right: 1px;
  width: 100%;
}

.relation-item {
  padding: 0px;
}

.el-divider {
  margin-top: 0px;
  margin-bottom: 20px;
}

.dialog-footer {
  padding-top: 10px;
  padding-left: 10%;
}

//布局样式区
.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>